import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  Keyboard,
  Image,
  TouchableWithoutFeedback,
  DeviceEventEmitter,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {LinearButton, LinearBoardButton} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import {createAuction} from '../../api/auction';
import moment from 'moment';
import ModalHandler from '../../components/ModalHandler';
import WalletUtils from '../../utils/wallet/WalletUtils';
import LayoutConstants from '../../config/LayoutConstants';
import {LinerBoardTextInput} from '../../components/TextInput';
import LinearGradient from 'react-native-linear-gradient';
import WalletConnectModal from '../../components/WalletConnectModal';

const NO_WIDTH_SPACE = '​'; // This is a special char you should copy and paste, not an empty string!

class Summary extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      loading: false,
      password: '',
      gasUsed: 0,
      success: false,
      approved: false,
      callFunc: '',
      queryingGas: false,
      queryingCreateGas: false,
      showWalletConnect: false,
      tx: undefined,
    };
  }

  componentDidMount() {
    //查询授权
    let {tokenId, contract, date} = this.props.navigation.state.params.nft;

    WalletUtils.queryNFTApproveAddress(tokenId, contract).then((res) => {
      console.log('查询到授权结果');
      console.log(res);
      console.log();

      if (res == this.props.proxy.address) {
        this.setState({
          approved: true,
        });
      }
    });
    console.log(this.props.navigation.state.params.nft);
  }

  handlerApprove = () => {
    Keyboard.dismiss();

    this.setState(
      {
        loading: true,
      },
      async () => {
        console.log(this.state.password);
        try {
          var privateKey = await WalletUtils.privateKeyOfKeystore(
            this.props.userInfo.keystore,
            this.state.password,
          );
        } catch (err) {
          console.log('错误' + err);
          this.setState(
            {
              modalVisible: false,
              loading: false,
            },
            () => {
              this._showAlert({content: 'invalid password'});
            },
          );
          return;
        }

        console.log(this.props.signinNFT);
        let {
          tokenId,
          contract,
          price,
          maxPrice,
          minIncreasePrice,
          payCoin,
          date,
        } = this.props.navigation.state.params.nft;

        let expireDate = parseInt(
          (new Date(date).valueOf() - new Date().valueOf()) / 1000,
        );

        console.log('时间差' + expireDate);

        if (this.state.approved) {
          WalletUtils.createAuction(
            privateKey,
            this.props.proxy.address,
            contract,
            tokenId,
            payCoin.contractAddress,
            price,
            minIncreasePrice,
            maxPrice,
            expireDate,
            'signin-app',
            payCoin.decimal,
            (hash) => {
              this.setState({
                result: '交易已发送，正在监听交易->' + hash,
              });
            },
          )
            .then((res) => {
              console.log(res);
              this.confirm({hash: res.hashId});
            })
            .catch((err) => {
              this.setState(
                {
                  modalVisible: false,
                  loading: false,
                },
                () => {
                  this._showAlert({content: 'failed,check your balance'});
                },
              );
            });
        } else {
          WalletUtils.approveNFT(
            privateKey,
            contract,
            this.props.proxy.address,
            tokenId,
            (hash) => {
              this.setState({
                result: '交易已发送，正在监听交易->' + hash,
              });
            },
          )
            .then((res) => {
              console.log(res);
              this.confirm({hash: res.hashId});
            })
            .catch((err) => {
              this.setState(
                {
                  modalVisible: false,
                  loading: false,
                },
                () => {
                  this._showAlert({content: 'failed,check your balance'});
                },
              );
            });
        }
      },
    );
  };

  _handlerView = () => {
    let {approved} = this.state;
    return (
      <View style={{width: '100%'}}>
        <Text
          style={{
            marginTop: 0,
            lineHeight: 40,
            color: '#6902F4',
            fontSize: 18,
          }}>
          {!approved ? 'Approve NFT Sell' : 'Create Auction'}
        </Text>
        <Text
          style={{
            lineHeight: 20,
            marginBottom: 10,
            color: '#4A4A4A',
          }}>
          {!approved
            ? 'To allow SIGNIN to sell items in your account. your must first complete a approve transation.'
            : 'You have Approved signin, now you need to create an auction transaction.'}
        </Text>
        <Image
          style={{height: 1, width: '100%', marginBottom: 20}}
          source={require('../../assets/auction/line.png')}></Image>
        <View style={{width: '100%'}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              marginTop: 0,
            }}>
            <Text style={{lineHeight: 30, color: '#6902F4'}}>
              Call Function
            </Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#6902F4',
                lineHeight: 30,
              }}>
              {this.state.callFunc}
            </Text>
          </View>
        </View>
        <View style={{width: '100%', marginBottom: 10}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              marginTop: 0,
            }}>
            <Text style={{lineHeight: 40, color: '#6902F4'}}>Gas Fee</Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#6902F4',
                lineHeight: 40,
              }}>{`${this.state.gasUsed}${this.props.gasSymbol}`}</Text>
          </View>
        </View>
        <LinerBoardTextInput
          placeholder="Your wallet password"
          secureTextEntry
          defaultValue={this.state.password}
          onChangeText={(text) => {
            this.setState({
              password: text,
            });
          }}
        />
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'flex-end',
            width: '100%',
            // marginTop: 10,
            marginBottom: 20,
          }}>
          <LinearBoardButton
            buttonStyle={{width: 100, height: 35, marginRight: 20}}
            text="Cancel"
            onPress={() => {
              this.setState({
                modalVisible: false,
              });
            }}
          />
          <LinearButton
            buttonStyle={{width: 100, height: 35, marginRight: 20}}
            text="Confirm"
            onPress={this.handlerApprove}
          />
        </View>
      </View>
    );
  };

  onPressBackground = () => {
    if (this.state.loading) {
      return;
    }

    this.setState({
      modalVisible: false,
      loading: false,
    });
  };

  showTxModal = () => {
    if (this.state.approved) {
      //改为wallet授权交易
      this.handleShowWalletConnectSignCreateAuction();
      return;

      this.setState({
        queryingCreateGas: true,
      });

      WalletUtils.getCreateAuctionGasPrice()
        .then((res) => {
          this.setState({
            queryingCreateGas: false,
            gasUsed: res,
            modalVisible: true,
            callFunc: 'createAuction',
          });
        })
        .catch((err) => {
          console.log('获取失败');
        });
    } else {
      //改为wallet授权交易
      this.handleShowWalletConnectSignApprove();
      return;

      this.setState({
        queryingGas: true,
      });

      WalletUtils.getRegisterNFTGasPrice()
        .then((res) => {
          this.setState({
            queryingGas: false,
            gasUsed: res,
            modalVisible: true,
            callFunc: 'approve',
          });
        })
        .catch((err) => {
          console.log('获取失败');
        });
    }
  };

  confirm = () => {
    if (!this.state.approved) {
      this.setState({
        success: true,
        approved: true,
      });
      setTimeout(() => {
        this.setState({
          modalVisible: false,
          success: false,
          loading: false,
        });
      }, 1 * 1000);
    } else {
      this.setState({
        success: true,
      });
      setTimeout(() => {
        this.setState(
          {
            modalVisible: false,
          },
          () => {
            // DeviceEventEmitter.emit('refreshHomeList');
            this.props.navigation.navigate('MyAuctions');
          },
        );
      }, 1000);
    }
  };

  highlight = (string) => {
    string.split(' ').map((word, i) => (
      <Text key={i}>
        <Text style={{color: '#8A7B6C'}}>{word} </Text>
        {NO_WIDTH_SPACE}
      </Text>
    ));
  };

  onPressWalletBackground = () => {
    this.setState({
      showWalletConnect: false,
    });
  };

  resultCall = (hash, err) => {
    if (err) {
      this.setState(
        {
          showWalletConnect: false,
        },
        () => {
          this._showAlert({content: err});
        },
      );
      return;
    }
    console.log('收到交易的HASH回调');
    console.log(hash);

    this.setState({
      showWalletConnect: false,
      modalVisible: true,
      loading: true,
    });

    WalletUtils.listenTx(hash)
      .then((res) => {
        console.log('交易已上链' + res);
        this.confirm();
      })
      .catch((err) => {
        console.log('交易失败');
        this.setState(
          {
            modalVisible: false,
            loading: false,
          },
          () => {
            this._showAlert({content: err?.message || err + ''});
          },
        );
      });
  };

  handleShowWalletConnectSignApprove = async () => {
    //生成交易
    this._showLoading();
    try {
      let {tokenId, contract} = this.props.navigation.state.params.nft;

      let tx = await WalletUtils.getApproveNFTTx(
        contract,
        this.props.proxy.address,
        tokenId,
        this.props.userInfo.metamaskAddress,
      );
      console.log(tx);
      this._hideLoading();
      //跳转
      this.setState({
        showWalletConnect: true,
        tx,
      });
    } catch (err) {
      this._hideLoading();
      this._showAlert({content: err?.msg || err + ''});
    }
  };

  handleShowWalletConnectSignCreateAuction = async () => {
    //生成交易
    this._showLoading();
    try {
      console.log(this.props.signinNFT);
      let {
        tokenId,
        contract,
        price,
        maxPrice,
        minIncreasePrice,
        payCoin,
        date,
      } = this.props.navigation.state.params.nft;

      let expireDate = parseInt(
        (new Date(date).valueOf() - new Date().valueOf()) / 1000,
      );

      console.log('时间差' + expireDate);

      let tx = await WalletUtils.getCreateAuctionTx(
        this.props.proxy.address,
        contract,
        tokenId,
        payCoin.contractAddress,
        price,
        minIncreasePrice,
        maxPrice,
        expireDate,
        'signin-app',
        payCoin.decimal,
        this.props.userInfo.metamaskAddress,
      );

      console.log(tx);
      this._hideLoading();
      //跳转
      this.setState({
        showWalletConnect: true,
        tx,
      });
    } catch (err) {
      this._hideLoading();
      this._showAlert({content: err?.msg || err + ''});
    }
  };

  renderComponent = () => {
    let {
      modalVisible,
      loading,
      success,
      approved,
      queryingGas,
      queryingCreateGas,
      showWalletConnect,
      tx,
    } = this.state;
    let {
      price,
      date,
      itemId,
      img,
      name,
      maxPrice,
      payCoin,
    } = this.props.navigation.state.params.nft;

    let top =
      500 +
      Math.sqrt(
        Math.pow(500, 2) - Math.pow(LayoutConstants.WINDOW_WIDTH / 2, 2),
      );

    return (
      <View style={{flex: 1, backgroundColor: '#fff'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Summary"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <View style={{padding: 20, flex: 1}}>
          <View
            style={{
              width: 1000,
              height: 1000,
              alignSelf: 'center',
              marginTop: -top,
              borderRadius: 500,
              backgroundColor: '#160231',
            }}></View>
          <Image
            style={{
              width: 90,
              height: 90,
              borderRadius: 10,
              alignSelf: 'center',
              marginTop: -30,
            }}
            source={{uri: img}}></Image>
          <Text
            style={{
              fontWeight: 'bold',
              color: '#8A7B6C',
              alignSelf: 'center',
              marginTop: 10,
            }}>
            {name}
          </Text>
          <View
            style={{
              height: 30,
              borderRadius: 20,
              backgroundColor: '#571DAA',
              position: 'relative',
              alignItems: 'center',
              justifyContent: 'center',
              marginTop: 20,
            }}>
            <Text style={{fontWeight: 'bold', color: 'white'}}>Summary</Text>
            <Image
              style={{position: 'absolute', right: 20, top: -14}}
              source={require('../../assets/auction/fee_tag.png')}></Image>
          </View>
          <Text
            style={{
              fontWeight: 'bold',
              fontSize: 18,
              color: '#7505F4',
              marginTop: 50,
            }}>
            Listing
          </Text>
          <Text
            style={{
              color: '#4A4A4A',
              marginBottom: 10,
              fontSize: 14,
              marginTop: 10,
            }}>
            Your item will be auctioned. the highest bidder will win it on
            {
              <Text style={{color: '#7505F4'}}>
                {' ' + moment(new Date(date)).format('YYYY-MM-DD HH:mm')}
              </Text>
            }
            . as long as their bid is at least
            {
              <Text style={{color: '#7505F4'}}>
                {' ' + price + payCoin.symbol}
              </Text>
            }
            .if there is no bid, the auction item will be returned.
          </Text>
          <Text
            style={{
              fontWeight: 'bold',
              fontSize: 18,
              color: '#7505F4',
              marginTop: 20,
            }}>
            Fees
          </Text>
          <Text
            style={{
              color: '#4A4A4A',
              marginBottom: 10,
              fontSize: 14,
              marginTop: 10,
            }}>
            Listing is free at the time of the sale,Sign Club will charge a
            {<Text style={{color: '#7505F4'}}> 10%</Text>} service fee.
          </Text>
          <Text
            style={{
              fontWeight: 'bold',
              fontSize: 18,
              color: '#7505F4',
              marginTop: 20,
            }}>
            In addition
          </Text>
          <Text
            style={{
              color: '#4A4A4A',
              marginBottom: 10,
              fontSize: 14,
              marginTop: 10,
            }}>
            If this NFT is the first auction after its creation, we will review
            it, which is expected to take
            {<Text style={{color: '#7505F4'}}> 1-2 </Text>}working days.
          </Text>
        </View>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center',
            marginBottom: 70,
          }}>
          <LinearButton
            buttonStyle={{
              width: '40%',
              marginRight: 10,
            }}
            loading={queryingGas}
            isDisabled={approved}
            text={'Approve'}
            onPress={this.showTxModal}
          />
          <Image
            style={{
              width: 30,
              height: 30,
              marginRight: 10,
              marginTop: 20,
              alignSelf: 'center',
            }}
            source={require('../../assets/auction/next_step.png')}
          />
          <LinearButton
            isDisabled={!approved}
            loading={queryingCreateGas}
            buttonStyle={{width: '40%'}}
            text={'Create Auction'}
            onPress={this.showTxModal}
          />
        </View>
        <ModalHandler
          visible={modalVisible}
          loading={loading}
          success={success}
          handlerView={this._handlerView}
          onPressBackground={this.onPressBackground}
        />
        <WalletConnectModal
          visible={showWalletConnect}
          resultCall={this.resultCall}
          onPressBackground={this.onPressWalletBackground}
          tx={tx}></WalletConnectModal>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  signinNFT: state.Chain.signinNFT,
  proxy: state.Chain.proxy,
  gasSymbol: state.Chain.gasSymbol,
  swapSymbol: state.Chain.swapSymbol,
  navigationStack: state.Layout.navigationStack,
});

const mapDispatchToProps = (dispatch) => ({
  userLogout: (item) => dispatch(userLogout()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Summary);
